<?php


namespace app\common\lib;


class Arr
{

    /**
     * 无限级分类
     * @param $data 所有数据
     * @return array
     */
    public static function getTree($data)
    {
        $items = [];
        //将ID改为键名
        foreach ($data as $v) {

            $items[$v['category_id']] = $v;
        }
        // halt($items);
        $tree = [];
        foreach ($items as $id => $item) {
            if (isset($items[$item['pid']])) {  //$item是否存在  PID
                $items[$item['pid']]['list'][] = &$items[$id]; //$items[$id] 等于$items数据
            } else {
                $tree[] = &$items[$id];
            }
        }
        return $tree;
    }

    /**
     * 无限级分类截取
     * @param $data
     * @param int $firstCount
     * @param int $secondCount
     * @param int $threeCount
     * @return array
     */
    public static function sliceTreeArr($data, $firstCount = 5, $secondCount = 3, $threeCount = 5)
    {
        //一级分类截取从开头截取 截取到第5个
        $data = array_slice($data, 0, $firstCount);
        //二级分类截取
        foreach ($data as $k => $v) {
            if (!empty($v['list'])) {
                $data[$k]['list'] = array_slice($v['list'], 0, $secondCount);
                //三级分类截取
                foreach ($data[$k]['list'] as $kk => $vv) {
                    if (!empty($vv['list'])) {
                        $data[$k]['list'][$kk]['list'] = array_slice($vv['list'], 0, $threeCount);
                    }
                }
            }
        }
        return $data;
    }


    /**
     * 异常默认 返回分页
     * @return array
     */
    public static function getPaginateDefaultData()
    {
        $result = [
            "total" => 0,
            "per_page" => 5,
            "current_page" => 1,
            "last_page" => 0,
            "data" => [],
        ];
        return $result;
    }

    /**
     * 数组排序
     * @param $result  数组
     * @param $key 排序字段
     * @param int $sort 排序顺序
     * @return array|bool
     */
    public static function arrsSortByKey($result, $key, $sort = SORT_DESC)
    {
        if (!is_array($result) || !$key) {
            return [];
        }
        array_multisort(array_column($result, $key), $sort, $result);
        return $result;
    }

}